//
//  Calling.m
//  ZhumuSDKSample
//
//  Copyright 2006-2015 SUIRUI Co., Ltd. All rights reserved.
//

#import "Calling.h"

@implementation Calling
+(void)startCall:(Meeting *)info delegate:(id<ZhumuSDKMeetingServiceDelegate>)delegate success:(CALL_SUCCESS)success failure:(CALL_FAILURE)failure
{
    
}
@end


////////////////////////////////////////////////////////////////////////


@interface RequestCalling()

typedef void (^REQUEST_SUCCESS)(MeetingFullInfo *meeting);
typedef void (^REQUEST_FAILURE)(NSString *error);

@property (strong,nonatomic) NSMutableData *myResult;
@property (copy,nonatomic) REQUEST_SUCCESS successR;
@property (copy,nonatomic) REQUEST_FAILURE failureR;

@end

@implementation RequestCalling
//网络请求超时时间
static const CGFloat request_timeout = 8.f;
//服务器地址
static NSString *server_url = @"https://api.zhumu.me/v1/user/get";

-(void)requestData:(RequestMeeting *)info success:(REQUEST_SUCCESS)success failure:(REQUEST_FAILURE)failure
{
//    self.successR = success;
//    self.failureR = failure;
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    NSDictionary *parameters = @{@"api_key":info.api_key, @"api_secret":info.api_secret, @"logintype":@(info.login_type),@"loginname":info.login_name};
    [sessionManager POST:server_url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

//        NSString *receiveStr = ZM_AUTORELEASE([[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
//        NSLog(@"%@",receiveStr);
        //解析
        success(ZM_AUTORELEASE([[MeetingFullInfo alloc] initWithDictData:responseObject]));

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([error localizedDescription]);
    }];

    
//    NSString *urlStr = [NSString stringWithFormat:@"%@",server_url];
//    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSURL *url = [NSURL URLWithString:urlStr];
//    NSMutableURLRequest *requestM = ZM_AUTORELEASE([[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:request_timeout]);
//    //设置post请求
//    [requestM setHTTPMethod:@"POST"];
//    //设置参数
//    NSString *bodyDataStr=[NSString stringWithFormat:@"api_key=%@&api_secret=%@&logintype=%ld&loginname=%@",
//                           info.api_key, info.api_secret, (long)info.login_type, info.login_name];
//    NSData *bodyData=[bodyDataStr dataUsingEncoding:NSUTF8StringEncoding];
//    [requestM setHTTPBody:bodyData];
//    
//    //发送异步请求,针对HTTPS
//    NSURLConnection *connection = ZM_AUTORELEASE([[NSURLConnection alloc] initWithRequest:requestM delegate:self]);
//    [connection start];
}

//-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//    //NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
//    //NSLog(@"%@",[res allHeaderFields]);
//    self.myResult = [NSMutableData data];
//}
//
////接收到服务器传输数据的时候调用，此方法根据数据大小执行若干次
//-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
//{
//    [self.myResult appendData:data];
//}
//
////数据传输完成之后执行方法
//-(void)connectionDidFinishLoading:(NSURLConnection *)connection
//{
//    NSString *receiveStr = ZM_AUTORELEASE([[NSString alloc]initWithData:self.myResult encoding:NSUTF8StringEncoding]);
//    NSLog(@"%@",receiveStr);
//    //解析
//    _successR(ZM_AUTORELEASE([[MeetingFullInfo alloc] initWithJSONData:self.myResult]));
//    self.successR = nil;
//    self.failureR = nil;
//    self.myResult = nil;
//}
//
////网络请求时出现错误（断网，连接超时)执行方法
//-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
//{
//    NSLog(@"%@",[error localizedDescription]);
//    //无法连接至服务器
//    _failureR([error localizedDescription]);
//    self.successR = nil;
//    self.failureR = nil;
//    self.myResult = nil;
//}
//
////针对SSL认证
//- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{
//    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
//}
//
////接受任何证书
//- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
//    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
//}

#if !__has_feature(objc_arc)
-(void)dealloc
{
    self.successR = nil;
    self.failureR = nil;
    self.myResult = nil;
    [super dealloc];
}
#endif

@end


////////////////////////////////////////////////////////////////////////


@implementation InstantCalling
+(void)startCall:(RequestMeeting *)info delegate:(id<ZhumuSDKMeetingServiceDelegate>)delegate success:(CALL_SUCCESS)success failure:(CALL_FAILURE)failure
{
    //1.获取信息 post
    InstantCalling *instant = ZM_AUTORELEASE([[InstantCalling alloc] init]);
    [instant requestData:info success:^(MeetingFullInfo *meeting) {
        
        //2.呼叫
        if (100 == meeting.code) {
            ZhumuSDKMeetingService *ms = [[ZhumuSDK sharedSDK] getMeetingService];
            if (ms)
            {
                ms.delegate = delegate;
                ZhumuSDKMeetError ret;
                
                //注意: 开启即时会议,目前只有 ZhumuSDKUserType_ZoomUser 以及 ZhumuSDKUserType_SSOUser可以开启即时会议.
                ret = [ms startInstantMeeting:meeting.userID userToken:meeting.token userType:ZhumuSDKUserType_ZoomUser displayName:meeting.userName];
                
                NSLog(@"onMeetNow ret:%d", ret);
                success(meeting);
                
            } else {
                failure(@"SDK初始化失败");
            }
        } else {
            if (200 == meeting.code) {
                failure(meeting.msg);
            } else {
                failure([NSString stringWithFormat:@"数据错误[code:%ld]",(long)meeting.code]);
            }
        }
        
    } failure:^(NSString *error) {
        failure(error);
    }];
}
@end


////////////////////////////////////////////////////////////////////////


@implementation JoinCalling
+(void)startCall:(MeetingInfo *)info delegate:(id<ZhumuSDKMeetingServiceDelegate>)delegate success:(CALL_SUCCESS)success failure:(CALL_FAILURE)failure
{
    ZhumuSDKMeetingService *ms = [[ZhumuSDK sharedSDK] getMeetingService];
    if (ms)
    {
        ms.delegate = delegate;
        ZhumuSDKMeetError ret;
        
        //注意: 会议号入会
        ret = [ms joinMeeting:info.meetingID displayName:info.userName];
        
        NSLog(@"onMeetNow ret:%d", ret);
        success(info);
        
    } else {
        failure(@"SDK初始化失败");
    }
}
@end


////////////////////////////////////////////////////////////////////////


@implementation ScheduledCalling
+(void)startCall:(RequestMeeting *)info delegate:(id<ZhumuSDKMeetingServiceDelegate>)delegate success:(CALL_SUCCESS)success failure:(CALL_FAILURE)failure
{
    //1.获取信息 post
    ScheduledCalling *p2p = ZM_AUTORELEASE([[ScheduledCalling alloc] init]);
    [p2p requestData:info success:^(MeetingFullInfo *meeting) {
        
        //2.呼叫
        if (100 == meeting.code) {
            ZhumuSDKMeetingService *ms = [[ZhumuSDK sharedSDK] getMeetingService];
            if (ms)
            {
                ms.delegate = delegate;
                ZhumuSDKMeetError ret;
                
                //注意: 进入预约会议
                ret = [ms startMeeting:meeting.userID userToken:meeting.token userType:ZhumuSDKUserType_APIUser displayName:meeting.userName meetingNumber:meeting.meetingID];
                
                NSLog(@"onMeetNow ret:%d", ret);
                success(meeting);
                
            } else {
                failure(@"SDK初始化失败");
            }
        } else {
            if (200 == meeting.code) {
                failure(meeting.msg);
            } else {
                failure([NSString stringWithFormat:@"数据错误[code:%ld]",(long)meeting.code]);
            }
        }
        
    } failure:^(NSString *error) {
        failure(error);
    }];
}

@end